package com.rimuru.datastructure.binarytree.mybinarytree;

import com.rimuru.datastructure.binarytree.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 对称二叉树
 */
public class E04Leetcode101 {
    public boolean isSymmetric(TreeNode root) {
        return check(root.left, root.right);
    }


    /*
        1
       / \
      2   2
 */
    private boolean check(TreeNode left, TreeNode right) {
        if(left == null && right == null) {
            return true;
        } else if (left == null) {
            return false;
        } else if (right == null) {
            return false;
        } else if (left.val != right.val) {
            return false;
        } else {
            return check(left.left, right.right) && check(left.right, right.left);
        }
    }

    /**
     * 两个队列解法
     */

    public boolean isSymmetric1(TreeNode root) {
        if(root == null) {
            return false;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root.left);
        deque.add(root.right);
        while (!deque.isEmpty()) {
            TreeNode left = deque.poll();
            TreeNode right = deque.poll();
            if(left == null && right == null) {
                // 终止这次循环
                continue;
            }
            if(left == null || right == null || left.val != right.val) {
                return false;
            }
            deque.add(left.right);
            deque.add(right.left);
            deque.add(left.left);
            deque.add(right.right);
        }
        return true;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(
                new TreeNode(null, 2, new TreeNode(3)),
                1,
                new TreeNode(null, 2, new TreeNode(3))
        );
        System.out.println(new E04Leetcode101().isSymmetric(root));
        System.out.println(new E04Leetcode101().isSymmetric1(root));


        TreeNode root1 = new TreeNode(
                new TreeNode(new TreeNode(3), 2, new TreeNode(4)),
                1,
                new TreeNode(new TreeNode(4), 2, new TreeNode(3))
        );
        System.out.println(new E04Leetcode101().isSymmetric(root1));
        System.out.println(new E04Leetcode101().isSymmetric1(root1));
    }



    // 1,2,2,3,4,4,3,5,6,7,8,8,7,6,5
}
